package com.tan.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ServiceInterceptor implements MethodInterceptor {
    /**
     *
     * @param target 目标类的子类
     * @param method 目标类的方法
     * @param args  目标类方法的参数
     * @param methodProxy 执行目标类方法
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("===开始"+method.getName()+"=====");
        //执行原来的业务逻辑
        Object result = methodProxy.invokeSuper(target, args);
        System.out.println("===结束"+method.getName()+"=====");
        return result;
    }

    public static void main(String[] args) {
        //1.获得cglib的增强类
        Enhancer enhancer=new Enhancer();
        //2.设置目标类
        enhancer.setSuperclass(RoleService.class);
        //3.设置拦截器
        enhancer.setCallback(new ServiceInterceptor());
        //4.获得代理类
        RoleService roleService = (RoleService) enhancer.create();
        roleService.add();
        roleService.del();
    }
}
